//
//  RecoderShareCardController.m
//  QRMaster
//
//  Created by myApple on 15/7/29.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "RecoderShareCardController.h"
#import "RequestNetWork.h"
#import "PromptInfoView.h"
#import "RecoderShareCardCell.h"
#import "RecodeShareCardModel.h"
//#import "EditShareTimeViewController.h"
#import "Reachability.h"
#import "MJRefresh.h"
#import "HistroyShareCardController.h"
#import "EditTimeController.h"
#import "StartPageController.h"
#import "MJExtension.h"
#import "UserInfoLogic.h"
#import "userInfoModel.h"

@interface RecoderShareCardController ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView * shareCardTableView;
    NSMutableArray * shareCardArray;
    UIActivityIndicatorView * _activityIndicator;
    MJRefreshNormalHeader * _headerView;
    UIImageView * promtBackView;
    
    NSString * userAreaCode;//用户的区号
    
    //多语言
    UILabel * titleNameLabel;
    UIButton * histroyBtn;
    UILabel * promtLabel;
}

@end

@implementation RecoderShareCardController

- (void)viewDidLoad {
    [super viewDidLoad];
    shareCardArray = [[NSMutableArray alloc]init];
    [self getDataFromDisk];
    [self prepareTitleView];
    [self prepareTableView];
    [self preparePromtView];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    histroyBtn.hidden = NO;
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self prepareData];
    self.navigationItem.title = NSLocalizedString(@"todayShare", nil);
    [histroyBtn setTitle:NSLocalizedString(@"histroyShare", nil) forState:0];
    promtLabel.text = NSLocalizedString(@"clickRefresh", nil);
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    histroyBtn.hidden = YES;
}

-(void)getDataFromDisk
{
    __block userInfoModel *userModel = [[userInfoModel alloc]init];
    UserInfoLogic *userLogic = [[UserInfoLogic alloc]init];
    
    [userLogic queryUserInfo:^(userInfoModel *myUserModel)
     {
         userModel =myUserModel;
     }
     ];
    userAreaCode = userModel.areaCode;
}


-(void)prepareTitleView
{
    histroyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    histroyBtn.frame = CGRectMake(UI_SCREEN_WIDTH-80, 0, 80, 40);
    [histroyBtn setTitle:NSLocalizedString(@"histroyShare", nil) forState:0];
    [histroyBtn setTitleColor:[UIColor whiteColor] forState:0];
    histroyBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [histroyBtn addTarget:self action:@selector(lookHistroy:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:histroyBtn];
}

-(void)preparePromtView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = ScreenHeight - 64;
    promtBackView = [[UIImageView alloc]initWithFrame:CGRectMake(x,y, width, height)];
    promtBackView.backgroundColor = RGBA(237, 238, 241, 1);
    promtBackView.userInteractionEnabled = YES;
    promtBackView.hidden = YES;
    [self.view addSubview:promtBackView];
    UITapGestureRecognizer * imgViewTap  = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backViewClick:)];
    [promtBackView addGestureRecognizer:imgViewTap];
    
    x = 0;
    width = ScreenWidth;
    y = ScreenHeight / 2.0 - 10;
    height = 20;
    promtLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    promtLabel.text = NSLocalizedString(@"clickRefresh", nil);
    promtLabel.textColor = RGBA(143, 147, 148, 1);
    promtLabel.textAlignment = NSTextAlignmentCenter;
    [promtBackView addSubview:promtLabel];
    
}

-(void)backViewClick:(UITapGestureRecognizer *)tap
{
    promtBackView.hidden = YES;
    [self prepareData];
}

-(void)lookHistroy:(UIButton *)btn
{
    HistroyShareCardController * hscc = [[HistroyShareCardController alloc]init];
    hscc.userAreaCode = userAreaCode;
    [self.navigationController pushViewController:hscc animated:YES];
}

-(void)prepareData
{
    if ([self IsHaveNetwork]) {
        [shareCardTableView.mj_header endRefreshing];
        return;
    }
    [self startWaiting:nil color:nil addToView:self.view];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:@"1" forKey:@"today"];
    [rnk initWithPath:POST(NEWSHARELIST) params:postDict block:^(id downLoadData, id error) {
        [self stopWaiting];
        if ([downLoadData objectForKey:@"data"] != nil)
        {
            [shareCardArray removeAllObjects];
            for (NSDictionary * dict in [downLoadData objectForKey:@"data"]) {
                RecodeShareCardModel * model = [[RecodeShareCardModel alloc]init];
                model = [RecodeShareCardModel mj_objectWithKeyValues:dict];
                model.shareId = [dict objectForKey:@"id"];
                [shareCardArray addObject:model];
            }
            if (shareCardArray.count == 0)
            {
                promtBackView.hidden = NO;
                [PromptInfoView showMessage:NSLocalizedString(@"noShareList", nil)];
            }
        }
        else if (error != nil)
        {
                [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
        [shareCardTableView.mj_header endRefreshing];
        [shareCardTableView reloadData];
    }];
}

-(void)prepareTableView
{
    shareCardTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    shareCardTableView.dataSource = self;
    shareCardTableView.delegate = self;
    shareCardTableView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:shareCardTableView];
    shareCardTableView.mj_header =[MJRefreshHeader headerWithRefreshingBlock:^{
        [self prepareData];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return shareCardArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * string = @"cell";
    RecoderShareCardCell * cell = [tableView dequeueReusableCellWithIdentifier:string];
    if (!cell) {
        cell = [[RecoderShareCardCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    RecodeShareCardModel * model = shareCardArray[indexPath.row];
    cell.communityName = model.communityName;
    cell.communityId = model.communityId;
    cell.bulidingName = model.buildName;
    cell.floorName = model.floorName;
//    cell.roomId = model.roomId;
    if ([model.areaCode isEqualToString:userAreaCode]) {
        cell.shareMobile = model.mobile;
    }
    else
    {
        cell.shareMobile = [NSString stringWithFormat:@"+%@ %@",model.areaCode,model.mobile];
    }
    cell.roomName = model.roomName;
    cell.beginTime = model.startTime;
    cell.endTime = model.endTime;
    cell.status = model.status;
    cell.shareId = model.shareId;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    RecodeShareCardModel * model = shareCardArray[indexPath.row];
    if (model.status == 1) {
        EditTimeController * etvc = [[EditTimeController alloc]init];
        etvc.communityId = model.communityId;
//        etvc.roomId = model.roomId;
        etvc.beginTime = model.startTime;
        etvc.endTime = model.endTime;
        etvc.shareId = model.shareId;
        [self.navigationController pushViewController:etvc animated:YES];
    }
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    RecodeShareCardModel * model = shareCardArray[indexPath.row];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:model.shareId forKey:@"shareId"];
    [postDict setValue:model.communityId forKey:@"communityId"];
    [rnk initWithPath:POST(DELETESHARE) params:postDict block:^(id downLoadData, id error) {
        if ([downLoadData objectForKey:@"data"] != nil)
        {
            [shareCardArray removeObjectAtIndex:indexPath.row];
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationTop];
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
    }];
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RecodeShareCardModel * model = shareCardArray[indexPath.row];
    if (model.status == 1) {
        return NSLocalizedString(@"deleteCell", nil);
    }
    else
    {
        return NSLocalizedString(@"delete", nil);
    }
    
}

//初始化风火轮
-(void)prepareActivityIndicator
{
    _activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _activityIndicator.frame = CGRectMake(self.view.frame.size.width / 2.0 -15, self.view.frame.size.height / 2.0 - 15, 30, 30);
    _activityIndicator.hidden = NO;
    [self.view addSubview:_activityIndicator];
}
@end
